package edu.colorado.karl.login;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import edu.colorado.karl.databases.UserDatabaseConnector;

/**
 * This class provides password changing functionality for all users.
 * It reads and writes the 'user_data' table in the 'Users' database.
 * @author Addison LeMessurier
 * @version 5/4/08
 */

public class ChangePassword {
	private static Connection connection; // creates a connection to the SQL
	private static ChangePassword ref; // the only allowable reference to this class
	private static Statement statement; // used to execute SQL queries

	/**
	 * This function changes a user's password.
	 * @param username The name of the user.
	 * @param new_password The new password to use.
	 * @return a status message indicating the results of the operation.
	 */
	public static String changePass(String username, String new_password) {
		String password_hash = LoginUtil.MD5(new_password);
		String update = "UPDATE user_data SET password = '" + password_hash
				+ "' WHERE username = '" + username + "';";

		// do some checking to eliminate bad passwords
		if (new_password.length() < 6) {
			// error: password too short
			System.out.println("Error, new password is too short.");

			return "too short";
		}

		if (new_password.length() > 12) {
			// error: password too long
			System.out.println("Error, new password is too long.");

			return "too long";
		}

		try {
			connection = UserDatabaseConnector.getConnection();
			
			if(connection != null)
				statement = connection.createStatement();
		} catch (SQLException e) {
			// couldn't create statement
			System.out.println(e);
			return "statement error";
		}

		try {
			statement.executeUpdate(update);
		} catch (SQLException e) {
			// update didn't work
			System.out.println(e);
			return "SQL error";
		}

		UserDatabaseConnector.closeConnection(connection);
		return "success";
	}

	/**
	 * This function instantiates the singleton object for this class.
	 * @return a globally shared instance of ChangePassword.
	 */
	public static synchronized ChangePassword getChangePassword() {
		if (ref == null) {
			ref = new ChangePassword();
		}

		return ref;
	}

	private ChangePassword() {
		// empty for now
	}
}
